package cn.hf.mychat.controller;

import cn.hf.mychat.common.Ipoi.IExcelUtils;
import cn.hf.mychat.common.Ipoi.IUser;
import cn.hf.mychat.common.poi.ExcelUtils;
import cn.hf.mychat.config.Result;
import cn.hf.mychat.constanst.Test;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/hf")
@RequiredArgsConstructor
public class EnumTest {

    @GetMapping("enum")
    public ResponseEntity test(){
        Map<String, Object> map = new HashMap<>();
        map.put("success","真香");
        String s = Test.convertTemplateContent(map, Test.SUCCESS);
        System.out.println("s = " + s);
        return ResponseEntity.ok(s);
    }

    @PostMapping("/readExcel")
    public Result<String> readExcel(@RequestParam("file") MultipartFile file){
        String filename = file.getOriginalFilename();
        if (StringUtils.isEmpty(filename)){
            return Result.error("文件不存哎");
        }
        List<IUser> users = IExcelUtils.readExcel("a", IUser.class, file);

        System.out.println("users = " + users);
        return Result.success("上传成功！！");

    }

    /**
     * Excel导出
     * @param response
     */
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletRequest request, HttpServletResponse response){
        //使用假数据代替从数据库查出来的需要导出的数据
        List<IUser> empList = handleRepositoryData();
        long t1 = System.currentTimeMillis();
        IExcelUtils.writeExcel(request,response, empList, IUser.class);
        long t2 = System.currentTimeMillis();
        System.out.println(String.format("write over! cost:%sms", (t2 - t1)));
    }

    public List<IUser> handleRepositoryData() {
        List<IUser> empList = new ArrayList<>();
        IUser emp;
        for (int i = 1; i<= 10; i++) {
            emp = new IUser();
            emp.setId(i);
            emp.setUserName("员工" + i);
            emp.setPassword((1000 + i) + "");
            emp.setSalary(new BigDecimal(i * 1000 + ""));
            emp.setTime(LocalDateTime.now().minusHours(Long.valueOf(i)));
            empList.add(emp);
        }
        return empList;
    }
}
